<template>
  <div style="padding: 16px 20px;">
    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span style="font-size: 18px; font-weight: bold;">新增BOM</span>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        style="max-width: 800px;"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="BOM编号" prop="bomId">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input 
                  v-model="formData.bomId" 
                  placeholder="请输入BOM编号" 
                  :disabled="isSystemGenerated"
                  style="flex: 1;"
                />
                <el-checkbox 
                  v-model="isSystemGenerated" 
                  @change="handleSystemGeneratedChange"
                  style="margin-left: 8px;"
                >
                  系统编号
                </el-checkbox>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM主题" prop="bomTheme">
              <el-input v-model="formData.bomTheme" placeholder="请输入BOM主题" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成品编号" prop="productNumber">
              <el-input v-model="formData.productNumber" placeholder="请输入成品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入成品名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="formData.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品ID" prop="productId">
              <el-input v-model="formData.productId" placeholder="请输入产品ID" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formData.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="默认BOM" prop="defaultBOM">
              <el-select v-model="formData.defaultBOM" placeholder="请选择默认BOM" style="width: 100%;">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日产量" prop="dailyOutput">
              <el-input v-model="formData.dailyOutput" placeholder="请输入日产量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="false">
          <el-col :span="12">
            <el-form-item label="工艺流程ID列表" prop="processFlowIds">
              <el-input v-model="formData.processFlowIds" placeholder="请输入工艺流程ID列表，多个用逗号分隔" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- BOM配件部分 -->
      <div style="margin-top: 30px;">
        <h3 style="font-size: 16px; font-weight: bold; margin-bottom: 16px;">BOM配件</h3>
        

        <!-- 搜索区域 -->
        <div style="margin-bottom: 16px;">
          <el-input
            v-model="componentSearchKeyword"
            placeholder="请输入物品编号、名称或型号"
            clearable
            style="width: 300px;"
            @keyup.enter="handleComponentSearch"
          >
            <template #append>
              <el-button @click="handleComponentSearch">搜索</el-button>
            </template>
          </el-input>
        </div>

        <!-- 物品选择表格 -->
        <el-table 
          :data="componentItems" 
          v-loading="componentLoading" 
          border
          size="small"
          class="bom-table"
          @selection-change="handleComponentSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column prop="itemNumber" label="物品编号" min-width="120" />
          <el-table-column prop="itemName" label="物品名称" min-width="140" />
          <el-table-column prop="specificationModel" label="规格型号" min-width="160" />
          <el-table-column prop="unit" label="单位" width="100" />
          <el-table-column prop="brand" label="品牌" width="120" />
          <el-table-column label="*配件数量" width="120" align="center">
            <template #default="{ row }">
              <el-input 
                v-model="row.componentQuantity" 
                type="number" 
                placeholder="请输入数量"
                size="small"
                style="width: 80px;"
                min="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="损耗率" width="100" align="center">
            <template #default="{ row }">
              <el-input 
                v-model="row.lossRate" 
                type="number" 
                placeholder="0"
                size="small"
                style="width: 60px;"
                min="0"
                max="100"
              />
              <span style="margin-left: 4px;">%</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 12px;">
          <div>共 {{ componentTotalCount }} 条数据</div>
          <el-pagination
            background
            layout="sizes, prev, pager, next, jumper"
            :total="componentTotalCount"
            :current-page="componentPageIndex"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="componentPageSize"
            @size-change="handleComponentSizeChange"
            @current-change="handleComponentCurrentChange"
          />
        </div>
      </div>

      <!-- 工艺流程部分 -->
      <div style="margin-top: 30px;">
        <h3 style="font-size: 16px; font-weight: bold; margin-bottom: 16px;">工艺流程</h3>

        <el-table 
          :data="processFlowItems" 
          v-loading="processFlowLoading" 
          border
          @selection-change="handleProcessFlowSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column
            v-for="col in processFlowColumns"
            :key="col"
            :prop="col"
            :label="getProcessFlowColumnLabel(col)"
            :min-width="140"
            :formatter="processFlowCellFormatter"
          />
        </el-table>

        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 12px;">
          <div>共 {{ processFlowTotalCount }} 条数据</div>
          <el-pagination
            background
            layout="sizes, prev, pager, next, jumper"
            :total="processFlowTotalCount"
            :current-page="processFlowPageIndex"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="processFlowPageSize"
            @size-change="handleProcessFlowSizeChange"
            @current-change="handleProcessFlowCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, inject, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// BOM配件相关接口
interface ComponentItem {
  id: number
  itemNumber: string
  itemName: string
  specificationModel: string
  unit: string
  brand: string
  componentQuantity?: number
  lossRate?: number
}

interface ComponentQueryResponse {
  totaCount: number
  totaPage: number
  pageData: ComponentItem[]
  msg: string
  code: number
  data: unknown
}

interface ManagementModel {
  id: number
  bomId: string
  bomTheme: string
  productNumber: string
  productName: string
  specification: string
  productId: string
  unit: string
  brand: string
  defaultBOM: string
  dailyOutput: string
  itemIds: string | null
  processFlowIds: string | null
}

const formRef = ref<FormInstance>()
const loading = ref(false)

// BOM配件相关变量
const componentItems = ref<ComponentItem[]>([])
const selectedComponents = ref<ComponentItem[]>([])
const componentLoading = ref(false)
const componentSearchKeyword = ref('')
const componentPageIndex = ref(1)
const componentPageSize = ref(10)
const componentTotalCount = ref(0)

// 表单数据
const formData = reactive<Omit<ManagementModel, 'id'>>({
  bomId: '',
  bomTheme: '',
  productNumber: '',
  productName: '',
  specification: '',
  productId: '',
  unit: '',
  brand: '',
  defaultBOM: '',
  dailyOutput: '',
  itemIds: '',
  processFlowIds: ''
})

// 表单验证规则
const rules: FormRules = {
  bomId: [
    { required: true, message: '请输入BOM编号', trigger: 'blur' }
  ],
  bomTheme: [
    { required: true, message: '请输入BOM主题', trigger: 'blur' }
  ],
  productNumber: [
    { required: true, message: '请输入成品编号', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入成品名称', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请输入产品ID', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  brand: [
    { required: true, message: '请输入品牌', trigger: 'blur' }
  ],
  defaultBOM: [
    { required: true, message: '请选择默认BOM', trigger: 'change' }
  ],
  dailyOutput: [
    { required: true, message: '请输入日产量', trigger: 'blur' }
  ]
}

// 注入MainLayout的方法
const addTab = inject('addTab') as ((key: string, label: string) => void) | undefined
const switchTab = inject('switchTab') as ((key: string) => void) | undefined

// 系统编号复选框状态
const isSystemGenerated = ref(false)

// 生成系统BOM编号
const generateSystemBOMId = () => {
  const randomNum = Math.floor(Math.random() * 100)
  const paddedNum = String(randomNum).padStart(2, '0')
  return `BOM000${paddedNum}`
}

// 处理系统编号复选框变化
const handleSystemGeneratedChange = () => {
  if (isSystemGenerated.value) {
    // 选中时自动生成BOM编号
    formData.bomId = generateSystemBOMId()
  } else {
    // 取消选中时清空编号，允许手动输入
    formData.bomId = ''
  }
}

// 获取BOM配件列表
const fetchComponentItems = async () => {
  componentLoading.value = true
  try {
    const response = await axios.post<ComponentQueryResponse>(
      'http://localhost:5227/api/Item/query',
      {
        pageIndex: componentPageIndex.value,
        pageSize: componentPageSize.value,
        itemNumberOrNameOrModel: componentSearchKeyword.value
      },
      {
        headers: { 'Content-Type': 'application/json' }
      }
    )

    const res = response.data
    if (res.code === 200) {
      componentItems.value = res.pageData || []
      componentTotalCount.value = res.totaCount || 0
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  } catch (err: any) {
    console.error(err)
    ElMessage.error('请求失败，请检查后端接口')
  } finally {
    componentLoading.value = false
  }
}

// 处理BOM配件搜索
const handleComponentSearch = () => {
  componentPageIndex.value = 1
  fetchComponentItems()
}

// 处理BOM配件选择变化
const handleComponentSelectionChange = (selection: ComponentItem[]) => {
  selectedComponents.value = selection
  // 根据勾选的BOM配件，自动填充物品ID到itemIds中（逗号分隔）
  const ids = selectedComponents.value.map(s => String(s.id))
  formData.itemIds = ids.length > 0 ? ids.join(',') : ''
}

// 处理BOM配件分页大小变化
const handleComponentSizeChange = (size: number) => {
  componentPageSize.value = size
  componentPageIndex.value = 1
  fetchComponentItems()
}

// 处理BOM配件当前页变化
const handleComponentCurrentChange = (page: number) => {
  componentPageIndex.value = page
  fetchComponentItems()
}

// 添加BOM配件
const handleAddComponent = () => {
  if (selectedComponents.value.length === 0) {
    ElMessage.warning('请选择要添加的配件')
    return
  }
  
  // 检查是否填写了数量
  const invalidItems = selectedComponents.value.filter(item => !item.componentQuantity || item.componentQuantity <= 0)
  if (invalidItems.length > 0) {
    ElMessage.warning('请为选中的配件填写数量')
    return
  }
  
  ElMessage.success(`已添加 ${selectedComponents.value.length} 个配件`)
  // 这里可以添加将配件添加到BOM的逻辑
}

// 移除BOM配件
const handleRemoveComponent = () => {
  if (selectedComponents.value.length === 0) {
    ElMessage.warning('请选择要移除的配件')
    return
  }
  
  ElMessage.success(`已移除 ${selectedComponents.value.length} 个配件`)
  // 这里可以添加将配件从BOM中移除的逻辑
}

// 工艺流程 列表与分页
type AnyProcessFlow = Record<string, any> & { id?: number | string }

const processFlowItems = ref<AnyProcessFlow[]>([])
const processFlowLoading = ref(false)
const processFlowPageIndex = ref(1)
const processFlowPageSize = ref(10)
const processFlowTotalCount = ref(0)
const selectedProcessFlows = ref<AnyProcessFlow[]>([])

// 动态列：从首行数据中推断
const processFlowColumns = ref<string[]>([])

// 列名中文映射与辅助生成
const processFlowColumnLabelMap: Record<string, string> = {
  id: 'ID',
  processFlowNumber: '工艺流程编号',
  processFlowName: '工艺流程名称',
  processCount: '工序数量',
  responsiblePerson: '负责人',
  department: '部门',
  isActive: '是否启用',
  isActiveText: '启用状态',
  remarks: '备注',
  createdAt: '创建时间',
  updatedAt: '更新时间',
  attachmentOriginalFileName: '附件原文件名',
  attachmentStoredFileName: '附件存储文件名',
  attachmentPath: '附件路径',
  attachmentFilePath: '附件文件路径',
  attachmentFileSize: '附件大小',
  attachmentContentType: '附件类型',
  attachmentRemarks: '附件备注'
}

const getProcessFlowColumnLabel = (key: string): string => {
  if (processFlowColumnLabelMap[key]) return processFlowColumnLabelMap[key]
  if (key?.startsWith('attachment')) return '附件' + key.replace('attachment', '')
  return key
}

// 单元格格式化（布尔值转中文等）
const processFlowCellFormatter = (row: any, column: any, cellValue: any) => {
  const key = String(column?.property || '')
  if (key === 'isActive') {
    return cellValue ? '是' : '否'
  }
  return cellValue
}

const inferProcessFlowColumns = (rows: AnyProcessFlow[]) => {
  if (!rows || rows.length === 0) {
    processFlowColumns.value = []
    return
  }
  const sample = rows[0]
  const keys = Object.keys(sample)
    .filter(k => !['__v', 'id', 'Id'].includes(k))
    .filter(k => typeof sample[k] !== 'object')
  processFlowColumns.value = keys
}

// 获取工艺流程列表
const fetchProcessFlows = async () => {
  processFlowLoading.value = true
  try {
    const response = await axios.get(
      'https://localhost:7296/api/ProcessFlow',
      {
        params: {
          pageIndex: processFlowPageIndex.value,
          pageSize: processFlowPageSize.value
        }
      }
    )
    const res = response.data

    if (res && typeof res === 'object' && 'code' in res) {
      if ((res as any).code === 200) {
        processFlowItems.value = Array.isArray((res as any).pageData) ? (res as any).pageData : []
        processFlowTotalCount.value = Number((res as any).totaCount || (res as any).totalCount || 0)
        inferProcessFlowColumns(processFlowItems.value)
      } else {
        ElMessage.error((res as any).msg || '查询失败')
      }
    } else if (Array.isArray(res)) {
      processFlowTotalCount.value = res.length
      const start = (processFlowPageIndex.value - 1) * processFlowPageSize.value
      processFlowItems.value = res.slice(start, start + processFlowPageSize.value)
      inferProcessFlowColumns(processFlowItems.value)
    } else {
      const dataArr = Array.isArray((res as any)?.data) ? (res as any).data : []
      processFlowTotalCount.value = dataArr.length
      const start = (processFlowPageIndex.value - 1) * processFlowPageSize.value
      processFlowItems.value = dataArr.slice(start, start + processFlowPageSize.value)
      inferProcessFlowColumns(processFlowItems.value)
    }
  } catch (err: any) {
    console.error(err)
    ElMessage.error('请求失败，请检查工艺流程后端接口')
  } finally {
    processFlowLoading.value = false
  }
}

const handleProcessFlowSelectionChange = (selection: AnyProcessFlow[]) => {
  selectedProcessFlows.value = selection
  const ids = selectedProcessFlows.value
    .map(s => (s as any).Id ?? (s as any).id)
    .filter(v => v !== undefined)
    .map(v => String(v))
  formData.processFlowIds = ids.length > 0 ? ids.join(',') : ''
}

const handleProcessFlowSizeChange = (size: number) => {
  processFlowPageSize.value = size
  processFlowPageIndex.value = 1
  fetchProcessFlows()
}

const handleProcessFlowCurrentChange = (page: number) => {
  processFlowPageIndex.value = page
  fetchProcessFlows()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const response = await axios.post(
      'http://localhost:5233/api/Management/create',
      formData,
      {
        headers: { 'Content-Type': 'application/json' }
      }
    )

    const res = response.data
    if (res.code === 200) {
      ElMessage.success('BOM创建成功')
      // 跳转回BOM管理页面
      goBack()
    } else {
      ElMessage.error(res.msg || '创建失败')
    }
  } catch (error: any) {
    console.error('创建BOM失败:', error)
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('创建失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    isSystemGenerated.value = false // 重置时也清空系统编号复选框
  }
  // 重置BOM配件相关数据
  selectedComponents.value = []
  componentSearchKeyword.value = ''
  componentPageIndex.value = 1
}

// 返回BOM管理页面
const goBack = () => {
  if (addTab && switchTab) {
    addTab('bom-management', 'BOM管理')
    switchTab('bom-management')
  }
}

// 页面加载时获取BOM配件列表
onMounted(() => {
  fetchComponentItems()
  fetchProcessFlows()
})
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-right: 12px;
}

.el-card {
  margin-bottom: 20px;
}

/* 收紧BOM配件表格的行高与单元格内边距 */
.bom-table :deep(.el-table__cell) {
  padding: 4px 6px;
}
.bom-table :deep(.cell) {
  padding: 0 6px;
}
</style>
